import { fileURLToPath, URL } from 'node:url';
import { build, defineConfig, loadEnv } from 'vite';
import path from 'path';
import vue from '@vitejs/plugin-vue';
import vueDevTools from 'vite-plugin-vue-devtools';
// @ts-ignore
import postCssPxToRem from 'postcss-pxtorem';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { VantResolver } from '@vant/auto-import-resolver';
import removeConsole from 'vite-plugin-remove-console';
import { viteInjectAppLoadingPlugin } from './plugins/inject-app-loading';
import ElementPlus from 'unplugin-element-plus/vite';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { visualizer } from 'rollup-plugin-visualizer';
import viteCompression from 'vite-plugin-compression';
// import { dirname, resolve } from 'node:path';
// const __dirname = dirname(fileURLToPath(import.meta.url));
// console.log(__dirname);

const modeType: any = {
    dev: '/mamak/',
    test: '/mamak/',
    sit: '/mamak/',
    uat: '/',
    prod: '/',
};

export default defineConfig(({ mode, command }): any => {
    console.log(`---当前环境：【${mode}】---`);

    // const env = loadEnv(mode, process.cwd(), '');

    return {
        base: modeType[mode],

        plugins: [
            viteInjectAppLoadingPlugin(),
            vue(),
            AutoImport({
                resolvers: [
                    ElementPlusResolver({
                        importStyle: 'sass',
                    }),
                    VantResolver(),
                ],
            }),
            Components({
                resolvers: [
                    ElementPlusResolver({
                        importStyle: 'sass',
                    }),
                    VantResolver(),
                ],
            }),
            ElementPlus({
                useSource: true,
            }),
            createSvgIconsPlugin({
                iconDirs: [
                    path.resolve(process.cwd(), 'src/assets/svgs/common'),
                    path.resolve(process.cwd(), 'src/assets/svgs/home'),
                ],
                symbolId: 'icon-[dir]-[name]',
            }),
            // vueDevTools(),
            removeConsole(),
            viteCompression({
                algorithm: 'gzip', // 压缩算法
                ext: '.gz', // 生成后缀
                threshold: 10240, // 仅压缩大于 10KB 的文件
                deleteOriginFile: false, // 是否删除源文件（建议 false)
            }),
            visualizer({
                open: false, // 构建后自动打开
                gzipSize: true, // 显示 gzip 大小
                brotliSize: true, // 显示 brotli 大小（若环境支持）
                filename: 'stats.html', // 报告文件名
            }),
        ],
        // 添加 Worker 配置解决构建错误
        worker: {
            format: 'es',
            rollupOptions: {
                output: {
                    format: 'es',
                },
            },
        },
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            },
            extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
        },
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@use "@/assets/css/theme.scss" as *;`,
                },
            },
            // postcss: {
            //     plugins: [
            //         postCssPxToRem({
            //             // rootValue 必须和 html font-size 保持一致
            //             rootValue: 375 / 10, // 设计稿375px，rootValue=37.5
            //             unitPrecision: 3,
            //             // selectorBlackList: [/^\.ig/,/^\.el/],
            //             propList: ['*'], // 排除特定属性
            //             ignoreIdentifier: 'px-to-rem-ignore', // 自定义忽略标记
            //             // exclude: function (file: any) {
            //             //   return file.includes('home')
            //             // },
            //         }),
            //     ],
            // },
        },
        build: {
            rollupOptions: {
                output: {
                    // 入口 chunk：业务代码
                    entryFileNames: 'assets/js/[name]-[hash].js',
                    // 三方依赖：按包名各自独立分包，便于长期缓存
                    chunkFileNames: 'assets/js/[name]-[hash].js',
                    manualChunks: {
                        vue: ['vue', 'vue-router'],
                        'element-plus': ['element-plus'],
                        vant: ['vant'],
                    },
                },
            },
        },

        server: {
            host: '0.0.0.0',
            port: 5001,
            open: true,
            proxy: {
                // '/api': {
                //     target: 'https://esign-webapi.smartapp.net.cn',
                //     // rewrite: (path: string) => path.replace(/\/api/, ''),
                //     configure: (proxy: any, options: any) => {
                //         // 配置此项可在响应头中看到请求的真实地址
                //         proxy.on('proxyRes', (proxyRes: any, req: any) => {
                //             proxyRes.headers['x-real-url'] = new URL(req.url || '', options.target)?.href || '';
                //         });
                //     },
                // },
                '/rest': 'https://twines-web.smartapp.net.cn/WebApi',
            },
        },
    };
});
